# -*- coding: utf-8 -*-

import os
from distutils.file_util import *

class PickupObject:
    srcFolder = ""
    tarFolder = ""
    objCodes = []
    prefix = ['']
    
    def __init__(self, srcFolder, tarFolder, objCodes, prefix=['', 'AO_', 'GL_']):
        self.srcFolder = srcFolder
        self.tarFolder = tarFolder
        self.objCodes = objCodes
        if len(prefix) == 0:
            self.prefix = ['']
        else:
            self.prefix = prefix

    def Run(self):
        for root, dirs, files in os.walk(self.srcFolder):
            for filename in files:
                #print filename
                fn = os.path.splitext(filename)
                cmpstr = fn[0] and fn[0].upper() or ""
                for objCode in self.objCodes:
                    flcode = [pf for pf in self.prefix if cmpstr == pf + objCode]
                    if len(flcode) > 0:
                        #print os.path.join(root, filename)
                        path = self.tarFolder + root.replace(self.srcFolder, '')
                        if not os.path.exists(path):
                            os.makedirs(path)
                        print os.path.join(path, filename)
                        copy_file(os.path.join(root, filename), os.path.join(path, filename), update=0)
                        
from Tkinter import *

class WinApp:
    def __init__(self):
        self.root = Tk(className="オブジェクトコピーツール")
        font = ('ＭＳ ゴシック', 11, NORMAL)
        frame0 = Frame(self.root)
        frame0.pack(side=TOP)
        label0 = Label(frame0, text="コピー元フォルダ：", font=font)
        label0.pack(side=LEFT)
        self.srcDir = Entry(frame0, font=font, width=40)
        self.srcDir.pack(side=LEFT)
        self.findSrcDir = Button(frame0, text=u"参照", command=self.findSrcFolder, font=font)
        self.findSrcDir.pack(side=LEFT)
        
        frame1 = Frame(self.root)
        frame1.pack(side=TOP)
        frame1.pack(side=TOP)
        label1 = Label(frame1, text="コピー先フォルダ：", font=font)
        label1.pack(side=LEFT)
        self.tarDir = Entry(frame1, font=font, width=40)
        self.tarDir.pack(side=LEFT)
        self.findTarDir = Button(frame1, text=u"参照", command=self.findTarFolder, font=font)
        self.findTarDir.pack(side=LEFT)

        frame2 = Frame(self.root)
        frame2.pack(side=TOP)
        label2 = Label(frame2, text="ファイルリスト", font=font)
        label2.pack()
        
        frame3 = Frame(self.root)
        frame3.pack(side=TOP)
        self.ctrl = []
        
        for i in range(0, 20):
            frameTemp = Frame(frame3)
            frameTemp.pack(side=TOP)
            Label(frameTemp, text="%3d：" % (i+1), font=font).pack(side=LEFT)
            self.ctrl.append(Entry(frameTemp, fg="blue", font=font, width=40))
            self.ctrl[i].pack(side=RIGHT)

        frame4 = Frame(self.root)
        frame4.pack(side=TOP)
        self.execute = Button(frame4, text="開始", command=self.start, font=font)
        self.execute.pack(side=RIGHT)
        self.saveSettings = Button(frame4, text="設定の保存", command=self.save, font=font)
        self.saveSettings.pack(side=LEFT)
        self.getSettings()
        self.root.mainloop()

    def getSettings(self):
        try:
            settings = open(os.path.join(os.path.curdir, "pickobject.cfg"), "r").read().split('\n')
        except:
            return
        settings = [setting.decode('cp932') for setting in settings]
        for i in range(0, 22):
            settings.append('')
        setVal = lambda ctrl, val: (ctrl.delete(0, END), ctrl.insert(INSERT, val))
        if settings[0]:
            setVal(self.srcDir, settings[0])
        if settings[1]:
            setVal(self.tarDir, settings[1])

        for i in range(2, 22):
            if settings[i]:
                setVal(self.ctrl[i-2], settings[i])

    def save(self):
        fl = open(os.path.join(os.path.curdir, "pickobject.cfg"), "w")
        fl.write(self.srcDir.get().encode('cp932') + '\n')
        fl.write(self.tarDir.get().encode('cp932') + '\n')
        for i in range(0, 20):
            print i
            fl.write(self.ctrl[i].get().encode('cp932') + '\n')
        fl.close()

    def findSrcFolder(self):
        import tkFileDialog
        dlg = tkFileDialog.Directory()
        dlg.options['initialdir'] = self.srcDir.get()
        if dlg.show():
            self.srcDir.delete(0, END)
            self.srcDir.insert(INSERT, os.path.abspath(dlg.options['initialdir']))

    def findTarFolder(self):
        import tkFileDialog
        dlg = tkFileDialog.Directory()
        dlg.options['initialdir'] = self.tarDir.get()
        if dlg.show():
            self.tarDir.delete(0, END)
            self.tarDir.insert(INSERT, os.path.abspath(dlg.options['initialdir']))

    def start(self):
        objCodes = [ctrl.get().strip() for ctrl in self.ctrl if len(ctrl.get().strip()) > 0]
        #print objCodes
        srcDir = self.srcDir.get().strip()
        tarDir = self.tarDir.get().strip()
        if len(objCodes) > 0 and len(srcDir) > 0 and len(tarDir) > 0:
            if not os.path.exists(tarDir):
                os.makedirs(tarDir)
            
            pickup = PickupObject(srcDir, tarDir, objCodes)
            pickup.Run()
        else:
            pass

WinApp()
